package com.haier.npt.filter.authentication;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.haier.npt.authention.authc.AuthenticationInfo;
import com.haier.npt.authention.authc.SimpleAuthenticationInfo;
import com.haier.npt.common.JsonResult;
import com.haier.npt.exception.ExceptionCode;
import com.haier.npt.security.domain.SysApp;
import com.haier.npt.sso.client.LoginClient;
import com.haier.npt.sso.client.SysAppCacheClient;
import com.haier.npt.sso.client.UserClient;
import com.haier.npt.utils.JsonUtils;

/**
 * @Description:
 * @author: lixu
 * @date:   2018年7月12日 下午5:01:29   
 */
public class UserTokenAuthenticationFilter extends AbstractAuthenticationFilter{

	@Autowired
	private UserClient userClient ; 
	
	@Autowired
	private SysAppCacheClient sysAppCacheClient ;
	
	@Autowired
	private LoginClient loginClient;
	
	private Logger logger = LoggerFactory.getLogger(UserTokenAuthenticationFilter.class);

	@Override
	AuthenticationInfo doAuthenticate(String token, HttpServletRequest request, HttpServletResponse response) {
		if(!StringUtils.isEmpty(token)){
			/**
			 * 校验app是否正确
			 */
			JsonResult<List<SysApp>> appReuslt = sysAppCacheClient.findAppByToken(token);
			List<SysApp> apps = null ; 
			if (appReuslt.getCode() ==0){
				apps   = appReuslt.getData() ; 
			} else if (Integer.compare(appReuslt.getCode(), ExceptionCode.TOKEN_INVALID.getCode()) == 0){
				//缓存信息为空，校验请求信息中是否有appKey信息
				String appKey = request.getParameter("app_key");
				if (StringUtils.isEmpty(appKey)) {
					logger.error("校验appkey 未通过 , token {} ,返回结果{}",token , JsonUtils.toJSONString(appReuslt));
					return null ;
				}
				//有token和appKey，模拟登陆
				JsonResult<SysApp> sysAppJsonResult = loginClient.simulatedLogin(token, appKey);
				if (sysAppJsonResult.getCode() != 0) {
					logger.error("校验token未通过, token {}, 返回结果{}", token, JsonUtils.toJSONString(sysAppJsonResult));
					return null;
				}
				apps = new ArrayList<>();
				apps.add(sysAppJsonResult.getData());
			} else {
				logger.error("校验appkey 未通过 , token {} ,返回结果{}",token , JsonUtils.toJSONString(appReuslt));
				//appkey 校验没有通过
				return null ; 
			}
			//不为空校验Token是否合法
			JsonResult<Object> result  = userClient.getUserInfo(token);
			if(result.getCode() ==0){	
				//获取当前登录人
				return new SimpleAuthenticationInfo(result.getData(), apps,token) ; 
			}else{
				logger.error("校验Token失败, token {0} ,返回结果{1}",token , result);
			}
		}
		logger.error("参数错误 ,原因 [token 为空] ");
		return null ;
	}

	@Override
	public String filterType() {
		
		return "pre";
	}

	@Override
	public int filterOrder() {
		
		return 2;
	}
}
